<?php
require_once(DIR_LIBRARY."orm".DS."orm.php");
require_once(DIR_LIBRARY."orm".DS."acl".DS."permission.php");

class AclRole extends ORM
{
    protected $tablename = "role";
    protected $dsn = AclPermission::DSN;


    public function getAll()
    {
        $this->appendWhere(1);
        $rs = $this->execute();
        
        if (!$rs->isSuccess())
        {
            throw new Exception("db query fail");
        }
        
        $rows = array();
        while ($row = $rs->fetchRow())
        {
            $rows[$row["id"]] = $row;
        }

        return $rows;    
    }

    public function create()
    {
        if (!$this->getName())
        {
            throw new Exception("no name passed in");
        }

        if (!$this->getField("access_list"))
        {
            throw new Exception("access list is null");
        }

        $max_id = self::factory()->getMaxId();

        if (!$max_id)
        {
            $id = 1;
        }
        else
        {
            $id = $max_id * 2;
        }
        $this->setId($id);

        return parent::create();
    }

    public function setField($name, $value)
    {
        if ("access_list" == $name)
        {
            if (!$value)
            {
                throw new Exception("access ids can not be empty");
            }

            if (!is_array($value))
            {
                $value = array($value);
            }

            $value = AclPermission::buildListFromArray($value);
        }
        parent::setField($name, $value);
    }

    public function getField($name)
    {
        $value = parent::getField($name);
        if (("access_list" == $name) && !is_array($value))
        {
            $value = AclPermission::resolveList($value);
        }

        return $value;
    }

    public function update()
    {
        if (NULL !== $this->getName() && !$this->getName())
        {
            throw new Exception("must have name");
        }

        if (NULL !== $this->getField("access_list") && !$this->getField("access_list"))
        {
            throw new Exception("access list is null");
        }

        return parent::update();
    }

	public function isAllow($role_id, $access_id)
	{
		$access_list = self::$map[$role_id];

		return AclPermission::inList($access_id, $access_list);
	}

    public function formatRow($row)
    {
        if ($row && isset($row["access_list"]))
        {
            $row["access_list"] = AclPermission::resolveList($row["access_list"]);
        }

        return $row;
    }

    public static function factory($id = NULL)
    {
        return new self($id);
    }

} //end
